﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using System.Threading.Tasks;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using EnvDTE80;
using Microsoft.Build.Execution;
using System.Reflection;

namespace Crude.VisualStudioAddin.BuildEngine
{
    public class Engine
    {
        DTE2 m_applicationObject;

        public static Engine Instance = new Engine();

        public void Init(DTE2 applicationObject)
        {
            m_applicationObject = applicationObject;
        }

        public void Build(IList<string> projectsPath, string task, string actionName)
        {
            Task.Factory.StartNew(() =>
            {
                foreach (string projectPath in projectsPath)
                {
                    BuildSync(projectPath, task, actionName);
                }                
            });
        }

        public void Build(string projectPath, string task, string actionName)
        {
            Task.Factory.StartNew(() =>
            {
                BuildSync(projectPath, task, actionName);
            });
        }

        private void BuildSync(string projectPath, string task, string actionName)
        {
            ProjectCollection projectCollection = ProjectCollection.GlobalProjectCollection;

            BuildParameters parameters = new BuildParameters(projectCollection);
            parameters.UseSynchronousLogging = true;
            parameters.EnableNodeReuse = true;
            parameters.NodeExeLocation = Assembly.GetExecutingAssembly().Location;
            parameters.MaxNodeCount = 1;
            parameters.DetailedSummary = true;
            parameters.OnlyLogCriticalEvents = false;
            parameters.Loggers = new List<ILogger> { new Logger(m_applicationObject, actionName) };

            parameters.ToolsetDefinitionLocations = ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile;
            parameters.DetailedSummary = false;

            ICollection<Microsoft.Build.Evaluation.Project>
                msbuildProjects = projectCollection.GetLoadedProjects(projectPath);

            BuildRequestData buildRequestData =
                new BuildRequestData(msbuildProjects.First().CreateProjectInstance(), new string[] { task });

            BuildManager.DefaultBuildManager.Build(parameters, buildRequestData);
        }
    }
}
